<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            width: 100%;
            height: 100%;
            position: relative;
        }

        div {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            position: absolute;
            left: 0px;
            top: 0px;
        }
    </style>
</head>

<body>
    <div id="myDiv"></div>

    <script>
        let div = document.querySelector('div')
        moveDivWithArrows(div);
        function moveDivWithArrows(div) {
            const stepSize = 20; // 每次移动的步长
            const screenWidth = window.innerWidth;
            const screenHeight = window.innerHeight;
            let left = 0;
            let top = 0;

            document.addEventListener('keydown', function (event) {
                const keyCode = event.keyCode;

                switch (keyCode) {
                    case 37: // 左箭头键
                        left -= stepSize;
                        if (left < 0) left = 0; // 防止左侧超出屏幕
                        break;
                    case 38: // 上箭头键
                        top -= stepSize;
                        if (top < 0) top = 0; // 防止顶部超出屏幕
                        break;
                    case 39: // 右箭头键
                        left += stepSize;
                        if (left > screenWidth - div.offsetWidth) left = screenWidth - div.offsetWidth; // 防止右侧超出屏幕
                        break;
                    case 40: // 下箭头键
                        top += stepSize;
                        if (top > screenHeight - div.offsetHeight) top = screenHeight - div.offsetHeight; // 防止底部超出屏幕
                        break;
                    default:
                        break;
                }

                div.style.left = left + 'px';
                div.style.top = top + 'px';
                console.log('触发了');
            });
        }





    </script>
</body>

</html>